import { useState, useEffect } from "react";
import { queryFavoriteList, delFavorite } from "@/api/favorite";
import { ColumnsType } from "antd/es/table";
import { Table, message, Popconfirm } from "antd";


interface Favorite {
    id: number;
    chatHistory: {
        id: number;
        content: string;
        type: number;
        createTime: Date;
    }
}


export function Collection() {
    const [tableData, setTableData] = useState<Array<Favorite>>([]);
    const columns: ColumnsType<Favorite> = [
        {
            title: 'ID',
            dataIndex: 'id'
        },
        {
            title: '内容',
            render: (_, record) => (
                <div>
                    {
                        record.chatHistory.type === 0 ? record.chatHistory.content
                        : record.chatHistory.type === 1 ? <img src={record.chatHistory.content} style={{maxHeight: 200}} />
                        : <a href={ record.chatHistory.content } download>{record.chatHistory.content}</a>
                    }
                </div>
            )
        },
        {
            title: '发表时间',
            render:(_, record) =>(
                <div>{new Date(record.chatHistory.createTime).toLocaleString()}</div>
            )
        },
        {
            title: '操作',
            render: (_, record)=>{
                return <div>
                    <Popconfirm
                        title="你确定要删除这条记录吗?"
                        onConfirm={()=>{confirm(record.id)}}
                        okText="是"
                        cancelText="否"
                    >
                        <a href="#">删除</a>
                    </Popconfirm>
                </div>
            }
        }
    ]

    const query = async ()=>{
        try {
            const resp: any = await queryFavoriteList();
            setTableData(resp.map((item: Favorite)=>{
                return {
                    ...item,
                    key: item.id
                }
            }))
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后再试')
        }
    }
    const confirm = async (id: number)=>{
        try{
            await delFavorite(id);
            message.success("删除成功");
            query();
        }catch(error: any) {
            message.error(error?.data?.message || "系统繁忙，请稍后重试");
        }
    }

    useEffect(()=>{
        query();
    }, [])

    return <div className="favorite">
        <div className="favorite-table">
            <Table columns={columns} dataSource={tableData}></Table>
        </div>
    </div>
}